package com.lagou;


import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;

import java.util.*;

@Activate(group = {CommonConstants.CONSUMER})
public class TPMonitorFilter implements Filter {
    private static boolean flag = true;
    //分别存三个服务的请求耗时
    private List<Long> provider1 = new ArrayList<>();
    private List<Long> provider2 = new ArrayList<>();
    private List<Long> provider3 = new ArrayList<>();

    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        long start = System.currentTimeMillis();
        try{
            return invoker.invoke(invocation);
        }finally {
            long spend = System.currentTimeMillis()-start;
            String methodName = RpcContext.getContext().getMethodName();
            //不同的方法存入各自集合
            if("sayHello".equals(methodName)){
                provider1.add(spend);
            }else if("goodNight".equals(methodName)){
                provider2.add(spend);
            }else {
                provider3.add(spend);
            }
            if(flag){
                //5秒一次定时打印
                flag=false;
                new Timer().schedule(new TimerTask() {
                    @Override
                    public void run() {
                        Long provider1T90 = getaLong(provider1,0.9);
                        Long provider2T90 = getaLong(provider2,0.9);
                        Long provider3T90 = getaLong(provider3,0.9);
                        Long provider1T99 = getaLong(provider3,0.99);
                        Long provider2T99 = getaLong(provider3,0.99);
                        Long provider3T99 = getaLong(provider3,0.99);
                        System.out.println("当前T90:"+"[sayHello:"+provider1T90+"],"+"[goodNight:"+provider2T90+"],"+"[Evening:"+provider3T90+"]");
                        System.out.println("当前T99:"+"[sayHello:"+provider1T99+"],"+"[goodNight:"+provider2T99+"],"+"[Evening:"+provider3T99+"]");
                    }
                },500,5000);//延迟500ms执行，保证先有数据，每5秒打印一次
                //每分钟清空一次请求耗时
                new Timer().schedule(new TimerTask() {
                    @Override
                    public void run() {
                        provider1.clear();
                        provider2.clear();
                        provider3.clear();
                    }
                },60000,60000);//1分钟后执行，每隔1分钟重复，保证每次5秒打印都是最近1分钟内的数据
            }

        }
    }

    /**
     * 计算T90，T99
     * @param provider
     * @param d
     * @return
     */
    private Long getaLong(List<Long> provider,double d) {
            Collections.sort(provider);
            double ceil = Math.ceil(provider.size() * d);
            int index = new Double(ceil).intValue();
            return provider.get(index - 1);


    }
}
